﻿using Model;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Business
{
    public class DeliveryDetailBiz
    {
        public int SaveItem(DeliveryDetail item)
        {
            var dbContext = new Context();

            dbContext.DeliveryDetails.Add(item);
            dbContext.SaveChanges();

            return item.Id;
        }

        public void UpdateItem(DeliveryDetail item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public DeliveryDetail LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.DeliveryDetails
                    where item.Id == id
                    select item).First();
        }

        public void RemoveItem(List<DeliveryDetail> items)
        {
            var dbContext = new Context();

            string ids = string.Empty;

            foreach (var item in items)
            {
                ids += item.Id + ",";
            }

            if (ids.EndsWith(","))
            {
                ids = ids.Substring(0, ids.Length-1);

                string deleteCommand = string.Format(Constants.DeleteCommand, "DeliveryDetail", ids);
                dbContext.Database.ExecuteSqlCommand(deleteCommand);
            }            
        }

        public void RemoveItemsByDeliveryId(int id)
        {
            if (id > 0)
            {
                var dbContext = new Context();

                string deleteCommand = string.Format(Constants.DeleteDeliveryDetailCommand, id);
                dbContext.Database.ExecuteSqlCommand(deleteCommand);
            }
        }

        public List<DeliveryDetail> LoadItems()
        {
            var dbContext = new Context();
            return (from item in dbContext.DeliveryDetails
                    orderby item.Id
                    select item).ToList();
        }

        public List<int> GetByOrders(string orderIds, int deliveryId)
        {
            List<int> result = new List<int>();

            var dbContext = new Context();

            string selectCommand = string.Format(Constants.GetDeliveryDetailByOrdersCommand, orderIds, deliveryId);
            result = dbContext.Database.SqlQuery<int>(selectCommand).ToList();

            return result;
        }
    }
}
